<template>
  <div class="role">
    <page-search :searchFormConfig="searchFormConfig"></page-search>
    <page-content
      :contentTableConfig="contentTableConfig"
      page-name="role"
      @new-btn-click="handleNewData"
      @edit-btn-click="handleEditData"
    ></page-content>
    <page-modal
      ref="pageModalRef"
      :default-info="defaultInfo"
      :modal-config="modalConfig"
      page-name="role"
      :otherInfo="otherInfo"
    >
      <div class="menu-tree">
        <el-tree
          ref="elTreeRef"
          :data="menus"
          show-checkbox
          node-key="id"
          :props="{ children: 'children', label: 'name' }"
          @check="handleCheckChange"
        >
        </el-tree>
      </div>
    </page-modal>
  </div>
</template>

<script setup lang="ts">
import { contentTableConfig } from './config/content.config'
import { searchFormConfig } from './config/search.config'
import { modalConfig } from './config/modal.config'

import PageSearch from '@/components/page-search'
import PageContent from '@/components/page-content'
import PageModal from '@/components/page-modal'

import { usePageModal } from '@/hooks/use-page-modal'

import { useStore } from 'vuex'
import { computed } from '@vue/runtime-core'
import { ref, nextTick } from 'vue'
import { getMenuLeafNodeKeys } from '@/utils/map-menus'
import { ElTree } from 'element-plus'

const store = useStore()
const menus = computed(() => store.state.entireMenu)

const otherInfo = ref({})
const handleCheckChange = (data1: any, data2: any) => {
  const checkedKeys = data2.checkedKeys
  const halfCheckedKeys = data2.halfCheckedKeys

  const menuList = [...checkedKeys, ...halfCheckedKeys]
  otherInfo.value = { menuList }
}
//由于组件逻辑原因 需要只处理叶子节点 需要在mapMenus.ts做配置
const elTreeRef = ref<InstanceType<typeof ElTree>>()
const editCallback = (item: any) => {
  const leafKeys = getMenuLeafNodeKeys(item.menuList)
  //打开的同步时候无法及时绑定 需要nextTick
  nextTick(() => elTreeRef.value?.setCheckedKeys(leafKeys, false))
}

const [pageModalRef, defaultInfo, handleEditData, handleNewData]: [...any] =
  usePageModal(undefined, editCallback)
</script>

<style scoped lang="less">
.menu-tree {
  margin-left: 25px;
}
</style>
